package com.ctshk.rpc.insurance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.insurance.dto.InsuranceSellDTO;
import com.ctshk.rpc.insurance.entity.Insurance;
import com.ctshk.rpc.insurance.entity.InsuranceProduct;
import com.ctshk.rpc.insurance.mapper.InsuranceMapper;
import com.ctshk.rpc.insurance.mapper.InsuranceProductMapper;
import com.ctshk.rpc.insurance.req.InsuranceAdjustReq;
import com.ctshk.rpc.insurance.req.InsuranceSellReq;
import com.ctshk.rpc.insurance.service.IInsuranceProductService;
import io.seata.common.util.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 保险产品 服务实现类
 * </p>
 *
 * @author wangcy
 * @since 2021-01-26
 */
@DubboService
public class InsuranceProductServiceImpl extends ServiceImpl<InsuranceProductMapper, InsuranceProduct> implements IInsuranceProductService {

    @Autowired
    private InsuranceMapper insuranceMapper;

    @Override
    public List<InsuranceSellDTO> queryAll(List<Long> ids) {
        QueryWrapper<Insurance> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Insurance::getIsDeleted, 0).orderByDesc(Insurance::getGmtCreate);
        queryWrapper.lambda().eq(Insurance::getStatus, 1);
        if (CollectionUtils.isNotEmpty(ids)) {
            queryWrapper.lambda().in(Insurance::getId, ids);
        }
        return EntityUtil.copyList(insuranceMapper.selectList(queryWrapper), InsuranceSellDTO.class);
    }

    @Override
    public PageResponse<InsuranceSellDTO> queryList(InsuranceSellReq insuranceSellReq) {
        IPage<Insurance> iPage = new Page<>(insuranceSellReq.getPageNo(), insuranceSellReq.getPageSize());
        QueryWrapper<Insurance> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(insuranceSellReq.getName())) {
            queryWrapper.lambda().like(Insurance::getName, insuranceSellReq.getName());
        }
        queryWrapper.lambda().eq(Insurance::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(Insurance::getStatus, 1)
                .orderByDesc(Insurance::getGmtCreate)
                .select(Insurance::getId, Insurance::getName, Insurance::getProductTrait, Insurance::getCompanyName);
        IPage<Insurance> insuranceIPage = insuranceMapper.selectPage(iPage, queryWrapper);
        List<Insurance> records = insuranceIPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageResponse<>(new ArrayList<>(), iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
        }
        List<InsuranceSellDTO> insuranceProductDTOList = EntityUtil.copyList(insuranceIPage.getRecords(), InsuranceSellDTO.class);
        List<Long> ids = records.stream().map(Insurance::getId).collect(Collectors.toList());
        List<InsuranceProduct> insuranceProducts = baseMapper.selectList(new QueryWrapper<InsuranceProduct>().lambda()
                .in(InsuranceProduct::getInsuranceId, ids)
                .eq(InsuranceProduct::getIsDeleted, IsDeletedCode.NO.getCode())
                .select(InsuranceProduct::getId, InsuranceProduct::getInsuranceId, InsuranceProduct::getAdjustType, InsuranceProduct::getAmount,
                        InsuranceProduct::getPercent));
        for (InsuranceSellDTO insuranceSellDTO : insuranceProductDTOList) {
            for (InsuranceProduct insuranceProduct : insuranceProducts) {
                if (Objects.equals(insuranceSellDTO.getId(), insuranceProduct.getInsuranceId())) {
                    insuranceSellDTO.setAdjustType(insuranceProduct.getAdjustType());
                    insuranceSellDTO.setAmount(insuranceProduct.getAmount());
                    insuranceSellDTO.setPercent(insuranceProduct.getPercent());
                }
            }
        }
        return new PageResponse<>(insuranceProductDTOList, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }

    @Override
    public void updateAdjust(InsuranceAdjustReq req, Long userId) {
        List<Long> ids = req.getIds();
        List<InsuranceProduct> insuranceProducts = baseMapper.selectList(new QueryWrapper<InsuranceProduct>().lambda()
                .in(InsuranceProduct::getInsuranceId, ids)
                .eq(InsuranceProduct::getIsDeleted, IsDeletedCode.NO.getCode()));
        List<InsuranceProduct> insertInsuranceProductList = new ArrayList<>();
        // 构建价格规则
        BigDecimal amount = null;
        BigDecimal percent = null;
        if (Objects.equals(req.getAdjustType(), 0)) {
            amount = req.getAdjustValue();
        } else if (Objects.equals(req.getAdjustType(), 1)) {
            percent = req.getAdjustValue().divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
        }
        LocalDateTime now = LocalDateTime.now();
        for (Long id : req.getIds()) {
            boolean exist = false;
            for (InsuranceProduct insuranceProduct : insuranceProducts) {
                if (id.equals(insuranceProduct.getInsuranceId())) {
                    insuranceProduct.setModifiedId(userId);
                    insuranceProduct.setGmtModified(now);
                    insuranceProduct.setAdjustType(req.getAdjustType());
                    insuranceProduct.setAmount(amount);
                    insuranceProduct.setPercent(percent);
                    exist = true;
                    break;
                }
            }
            if (!exist) {
                InsuranceProduct insuranceProduct = new InsuranceProduct();
                insertInsuranceProductList.add(insuranceProduct);
                insuranceProduct.setId(id);
                insuranceProduct.setInsuranceId(id);
                insuranceProduct.setAdjustType(req.getAdjustType());
                insuranceProduct.setAmount(amount);
                insuranceProduct.setPercent(percent);
                insuranceProduct.setCreateId(userId);
                insuranceProduct.setGmtCreate(now);
                insuranceProduct.setModifiedId(userId);
                insuranceProduct.setGmtModified(now);
            }
        }
        super.updateBatchById(insuranceProducts);
        super.saveBatch(insertInsuranceProductList);
    }
}
